import { MenuItemConstructorOptions, BrowserWindow } from 'electron'
import { join } from 'path'
import { is } from '@electron-toolkit/utils'
import { sysMenuItems, menuGroups } from './sysMenu'
import { createEditMenuTemplate } from './editMenu'

// 处理新窗口的打开
const handleOpenWindow = (browserWindow: BrowserWindow, path: string) => {
  const win = new BrowserWindow({
    width: 600,
    height: 500,
    parent: browserWindow,
    modal: true,
    frame: false,
    resizable: false,
    minimizable: false,
    maximizable: false,
    show: false,
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      nodeIntegration: false,
      contextIsolation: true
    }
  })
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    win.loadURL(`${process.env['ELECTRON_RENDERER_URL']}/#${path}`)
  } else {
    win.loadFile(join(__dirname, '../renderer/index.html'), {
      hash: path
    })
  }
  // 当窗口准备好显示时，显示窗口
  // 这样可以避免加载过程中的白屏闪烁
  win.on('ready-to-show', () => {
    win.show()
  })

  win.on('close', () => {
    browserWindow.focus()
  })
}

// 创建菜单项处理函数
const createMenuItem = (menuItem: typeof sysMenuItems[0], mainWindow: BrowserWindow) => ({
  label: menuItem.meta.name,
  click: () => {
    if (menuItem.isWindow) {
      handleOpenWindow(mainWindow, menuItem.path)
    } else {
      mainWindow.webContents.send('navigate', menuItem.path)
    }
  }
})

export const createMenuTemplate = (mainWindow: BrowserWindow): MenuItemConstructorOptions[] => {
  
  // 创建系统菜单
  const sysMenuTemplate = menuGroups.map(group => ({
    label: group.label,
    submenu: group.items.map(itemName => {
      const menuItem = sysMenuItems.find(item => item.name === itemName)
      if (!menuItem) throw new Error(`Menu item ${itemName} not found`)
      return {
        ...createMenuItem(menuItem, mainWindow),
      }
    })
  }))

  // 合并菜单，将系统菜单添加到编辑菜单之后
  return [ ...sysMenuTemplate]
}
